package com.chinanet.auth;

import com.chinanet.entry.Account;
import com.chinanet.repository.account.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;

@Component
public class LoginAuthenticationManager implements AuthenticationManager {


    @Autowired
    private AccountRepository accountRepository;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        System.out.println(authentication.getCredentials());

        Account account = accountRepository.findByUsername(authentication.getPrincipal().toString());
        if (account != null) {
            if (authentication.getCredentials().equals(account.getPassword())) {
                System.out.println("认证成功");
                return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), account.getUser().getRoles().stream().map(r-> new SimpleGrantedAuthority(r.getName())).collect(Collectors.toList()));
            }else {
                throw new BadCredentialsException("密码错误");
            }
        }else{
            // 认证失败
            throw new BadCredentialsException("用户名不存在");
        }
    }
}
